package pa1.helloworld;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Calendar;


public class HelloServer extends UnicastRemoteObject implements Hello{

	private static final long serialVersionUID = -6778766180993153576L;
	private static final int DefaultPort = 1099;
	private Info info;

	public HelloServer() throws RemoteException {
		super();
		System.out.println("Created HelloServer object.");
		info = new InfoImpl();	
	}

	@Override
	public String HelloRMI(String user) throws RemoteException{
		return "Hello " + user + ", the current system time is " + 
				Calendar.getInstance().getTime().toString();
	}
	
	@Override
	public Info HelloRMI2() throws RemoteException{
		((InfoImpl)info).updateLastCalled();
		return info;
	}

	public static void main(String args[]){

		Registry reg = null;
		try {
			reg = LocateRegistry.createRegistry(DefaultPort);
		} catch (RemoteException e) {
			try {
				reg = LocateRegistry.getRegistry();
			} catch (RemoteException e2) {
				System.out.println("Registry could not be established" + e);
				System.exit(0);
			} // try-catch-e2
		} // try-catch-e
		System.out.println("Registry established");


		String port = Integer.toString(Registry.REGISTRY_PORT);
		if (args.length == 1) {
			port = args[0];
		} else if (args.length > 1) {
			System.out.println("Usage: java helloworld.HelloServer [port]");
			System.exit(1);
		}
		try {
			//System.setSecurityManager( new RMISecurityManager() );
			HelloServer helloServer = new HelloServer();
			reg.rebind(
					Hello.SERVICENAME,
					helloServer);
			System.out.println("Bound RMI object in local registry at port " + port);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
